import fs from 'node:fs'
import _path from 'node:path'

export default function staticDir(staticDir: string) {
  return async function (ctx: any, next: any) {
    if (ctx.request.method === 'GET' && /.*\.(?:webp|ico|png|jpg|jpeg)$/.test(ctx.request.path)) {
      const filePath = _path.join(staticDir, ctx.request.path)

      const data = await readFile(filePath)
      ctx.set('Content-Type', 'image/webp')
      ctx.response.body = data
    }
    else {
      return next()
    }
  }
}

function readFile(filePath: string) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) {
        reject(err)
      }
      else {
        resolve(data)
      }
    })
  })
}
